package com.qf;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.model.Article;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class test02 {
    @Autowired
    private TransportClient transportClient;
    @Autowired
    private ObjectMapper objectMapper;


    @Test
    public void demo01() throws Exception {
        BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
        long start = System.currentTimeMillis();
        for (long i = 0; i < 1000000; i++) {
            Article article = new Article();
            article.setTitle("华为手机很棒22"+i);
            article.setContent("华为手机真的很棒22"+i);
            article.setId(i);

            String s = objectMapper.writeValueAsString(article);

            IndexRequest indexRequest = new IndexRequest("blog03", "article", "" + i).source(s, XContentType.JSON);

            bulkRequestBuilder.add(indexRequest);
        }
        BulkResponse bulkResponse = bulkRequestBuilder.get();
        long end = System.currentTimeMillis();
        System.out.println("消耗了:"+(end-start)/1000);


        System.out.println("获取状态：" + bulkResponse.status());
        if (bulkResponse.hasFailures()) {
            System.out.println("还有些--->有错误");
        }
    }


    @Test
    public void demo02(){

        SearchResponse searchResponse = transportClient.prepareSearch("blog03")
                .setTypes("article")
                //.setQuery(QueryBuilders.matchAllQuery())
                .setQuery(QueryBuilders.queryStringQuery("机很").field("title"))
                .setSource(SearchSourceBuilder.searchSource().size(100)).get();

        SearchHits hits = searchResponse.getHits();
        System.out.println("命中数"+hits.getTotalHits());


        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        
    }




}
